var base_url = getApp().globalData.base_url
var cookie = getApp().globalData.cookie
var accountNumber = getApp().globalData.accountNumber
var app = getApp();
Page({
  data: {
    accountNumber: "",
    password: "",
  },

  // 获取账号
  accountNumberInput: function (e) {
    this.setData({
      accountNumber: e.detail.value
    })
  },

  // 获取输入密码 
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 登录处理
  login: function () {
    var that = this;
    // console.log(base_url)
    if (this.data.accountNumber.length == 0 || this.data.password.length == 0) {
      wx.showModal({
        title: "错误",
        content: "账号和密码不能为空"
      });
    } else if (!/^\d{9}$/.test(that.data.accountNumber)) {
      wx.showModal({
        title: "错误",
        content: "账号格式有误"
      })
    }

    //正则表达式
    else if (!/([0-9A-Za-z]{6,16}$)/.test(this.data.password)) {
      wx.showModal({
        title: "错误",
        content: "密码格式不正确"
      });
    } else {

      console.log();
      wx.request({
        url: base_url + '/users/cookies',
        data: {
          "accountNumber": that.data.accountNumber,
          "password": that.data.password
        },
        method: 'POST',
        header: {
          "content-type": 'application/x-www-form-urlencoded' 
        },

        success(res) {

          if (res.data.resultCode == 200) {
            // 存储 cookie 
            console.log(res);
            app.globalData.cookie = res.cookies[0];
            app.globalData.accountNumber = that.data.accountNumber;

            wx.switchTab({
              url: '/pages/details/details'
            })
            
          } else {
            wx.showModal({
              title: "错误",
              content: res.data.message
            });
          }
        }
      })
    }
  }
})


// wx.getStorage({
//   key: 'cookie',
//   success: (cookie)=>{
//     wx.request({
//       url: 'http://localhost:8080/api/v1/users/cookies',
//       data: {

//       },
//       header: {
//         'content-type':'application/json',
//         'cookie': cookie.data // 设置cookie
//       },
//       method: 'GET',
//       dataType: 'json',
//       responseType: 'text',
//       success: (result)=>{
//         // ...
//       },
//       fail: () => {
//         // ...
//       },
//     })
//   }
// })